<?php

namespace App\Crontab;

use Hyperf\DbConnection\Db;

class ZbtPriceUpdateCrontab
{
    public function execute()
    {
        try {
            logger()->info('----------开始:更新ZBT价格------' . date('Y-m-d H:i:s'));
            $settingCofig = \App\Setting\Model\SettingConfig::query()
                ->whereIn('key', ['zbt_update_price_ratio', 'zbt_premium_ratio', 'zbt_rmb_ratio'])
                ->pluck('value', 'key');
            $settingConfigPrice = $settingCofig['zbt_update_price_ratio'];//浮动比率
            $settingConfigPremium = $settingCofig['zbt_premium_ratio'];//浮动比率
            $settingConfigRmb = $settingCofig['zbt_rmb_ratio'];//浮动比率
            $page = 0;
            $limit = 100;
            do {
                $updatePriceData = [];  //更新价格与库存
                $updateStoreData = [];   //更新库存
                $sendMessageData = ['count' => 0, 'list' => []];   //发送消息的数理与信息
                $res = \App\Config\Model\ConfigProduct::query()
                    ->select(['id', 'name', 'english_name', 'price', 'origin_price', 'item_id'])
                    ->where('source_type', \App\Config\Model\ConfigProduct::SOURCE_TYPE_CSGO)
                    ->offset($page * $limit)
                    ->limit($limit)
                    ->get();
                $marketList = [];
                foreach ($res as $item) {
                    $marketList[] = $item->english_name;
                }
                $zbtRes = [];
                if (!empty($marketList)) {
                    //获取zbt产品价格列表
                    $zbtRes = \App\Lib\Library\ZbtQuery::queryPriceBathName($marketList);
                }

                //1.组合成更新数组
                foreach ($res as $key => $item) {
                    $originPrice = number_format($item->origin_price / \App\Lib\AdminEnum::PRICE_MULTIPLE, 2, '.', '');

                    $ratioPriceDiff = number_format($originPrice * $settingConfigPrice / 100, 2, '.', '');
                    $ratioPrice = $ratioPriceDiff==0.00 ? 0.01 : $ratioPriceDiff;
                    $minPrice = ($originPrice - $ratioPrice) > 0 ? ($originPrice - $ratioPrice) : 0;
                    $maxPrice = $originPrice + $ratioPrice;
                    if (empty($zbtRes[$item->item_id])) {
                        continue;
                    }
                    if ($zbtRes[$item->item_id]['price'] > $minPrice && $zbtRes[$item->item_id]['price'] <= $maxPrice) {
                        $zbtPrice = $zbtRes[$item->item_id]['price'];
                        //更新价格与库存
                        $updatePriceData[$item->item_id] = [
                            'price' => $originPrice,
                            'zbt_price' => ceil($zbtPrice * $settingConfigPremium * \App\Lib\AdminEnum::PRICE_MULTIPLE),
                            'zbt_origin_price' => (int)($zbtPrice * \App\Lib\AdminEnum::PRICE_MULTIPLE),
                            'zbt_rmb_price' => ceil($zbtPrice * $settingConfigPremium * $settingConfigRmb * \App\Lib\AdminEnum::PRICE_MULTIPLE),
                            'stock' => $zbtRes[$item->item_id]['quantity'],
                        ];

                    } else {
                        //更新库存
                        $updateStoreData[$item->item_id] = $zbtRes[$item->item_id]['quantity'];
                        $sendMessageData['list'][] = [
                            'id' => $item->id,
                            'price' => number_format($item->origin_price / \App\Lib\AdminEnum::PRICE_MULTIPLE, 2, '.', ''),
                            'zbt_price' => $zbtRes[$item->item_id]['price'],
                        ];
                    }
                }


                //2.组成更新sql语句
                if (!empty($updatePriceData)) {
                    $itemIds = []; //判断itemId进行修改
                    $updatePriceSql = 'update us_config_product set update_time=\'' . time() . '\', origin_price = case item_id ';  //更新价格与库存
                    foreach ($updatePriceData as $key => $itemPrice) {

                        $updatePriceSql = $updatePriceSql . ' when ' . $key . ' then ' . $itemPrice['zbt_origin_price'] . ' ';
                    }

                    $updatePriceSql = $updatePriceSql . " END,price = case item_id ";
                    foreach ($updatePriceData as $key => $itemPrice) {
                        $updatePriceSql = $updatePriceSql . ' when ' . $key . ' then ' . $itemPrice['zbt_price'] . ' ';
                    }
                    $updatePriceSql = $updatePriceSql . ' END,rmb_price = case item_id ';
                    foreach ($updatePriceData as $key => $itemPrice) {
                        $updatePriceSql = $updatePriceSql . ' when ' . $key . ' then ' . $itemPrice['zbt_rmb_price'] . ' ';
                    }
                    $updatePriceSql = $updatePriceSql . ' END,stock = case item_id ';
                    foreach ($updatePriceData as $key => $itemPrice) {
                        $updatePriceSql = $updatePriceSql . ' when ' . $key . ' then ' . $itemPrice['stock'] . ' ';
                        $itemIds[] = $key;
                    }

                    if (!empty($itemIds)) {
                        $updatePriceSql = $updatePriceSql . ' END WHERE item_id IN (' . implode(',', $itemIds) . ')';
                        Db::select($updatePriceSql);
                    }


                }
                if (!empty($updateStoreData)) {
                    $itemIds = [];//需更新库存Ids
                    $updateStoreSql = 'update us_config_product set update_time=\'' . time() . '\', stock = case item_id ';  //更新价格与库存
                    foreach ($updateStoreData as $key => $val) {
                        $updateStoreSql = $updateStoreSql . ' when ' . $key . ' then ' . $val . ' ';
                        $itemIds[] = $key;
                    }
                    if (!empty($itemIds)) {
                        $updateStoreSql = $updateStoreSql . 'END WHERE item_id IN (' . implode(',', $itemIds) . ')';
                        Db::select($updateStoreSql);
                    }
                    $sendMessageData['count'] = $sendMessageData['count'] + count($updateStoreData);
                }
                $page++;
            } while (!$res->isEmpty());

            //---钉钉通知，更新价格超浮动金额的数量与产品信息
            if (!empty($sendMessageData['count'])) {
                \Ziyanco\Library\Sms\DingDingMessage::send(json_encode($sendMessageData['list']), '【更新ZBT价格】');
                logger()->info('更新ZBT价格:发送钉钉：价格变动过大数据:' . json_encode($sendMessageData['list']));
            }

            logger()->info('----------结束:更新ZBT价格------' . date('Y-m-d H:i:s'));
        } catch (\Throwable $e) {
            $exceptionData = [
                'code' => $e->getCode(),
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ];
            \Ziyanco\Library\Sms\DingDingMessage::sendException(json_encode($exceptionData));
            logger()->info('异常：更新ZBT价格:' . json_encode($exceptionData));
        }


    }

    /**
     * 变价
     * @return void
     */
    public static function changePrice()
    {

    }

    /**
     * 变物
     * @return void
     */
    public static function changeMatter()
    {

    }


}